package com.abel.quiz.common;/**
 * Created by abel.lin on 2017/9/4.
 */

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author abel.lin
 * @date_time 2017/9/4 15:00
 * @description
 */
public class CookieUtil {
    public static Logger log = LoggerFactory.getLogger(CookieUtil.class);

    /**
     * @param
     * @description 添加cookie
     * @author abel.lin
     * @date_time 2017/9/4 16:02
     */
    public static void put(HttpServletResponse response, String key, Object obj){
        Cookie cookie = new Cookie(key.trim(), JSON.toJSONString(obj));
        cookie.setMaxAge(60*60);// 设置为30min
        cookie.setPath("/");
        response.addCookie(cookie);
        log.info("put cookie key="+key);
    }

    /**
     * @param
     * @description 获取cookie
     * @author abel.lin
     * @date_time 2017/9/4 16:02
     */
    public static <T> T get(HttpServletRequest request, String key, Class<T> clazz){
        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        if(null==cookies) {
            log.info("cookie is null");
        }else{
            if(StringUtils.isNotBlank(key)){
                for(Cookie cookie : cookies){
                    if(key.equals(cookie.getName())){
                        return JSON.parseObject(cookie.getValue(), clazz);
                    }
                }
            }
        }

        return null;
    }

    /**
     * @param
     * @description 移除cookie
     * @author abel.lin
     * @date_time 2017/9/4 16:02
     */
    public static void remove(HttpServletRequest request,HttpServletResponse response,String key){
        Cookie[] cookies = request.getCookies();
        if(null==cookies) {
            log.info("cookie is null");
        }else{
            if(StringUtils.isNotBlank(key)){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(key)){
                        cookie.setValue(null);
                        cookie.setMaxAge(0);// 立即销毁cookie
                        cookie.setPath("/");
                        response.addCookie(cookie);
                        log.info("remove cookie:"+cookie.getName());
                        break;
                    }
                }
            }
        }
    }

}
